#include "stdio.h"
#include "stdint.h"
#include "string.h"
#include "parameters.h"
#include "version.h"
#include "FeedFrame.h"
#include "FeedID.h"


static int8_t cFeedIDHeartbeat(void *pvDatas)
{
    FeedFrameType *ptypeFrame = pvDatas;
    int32_t iValue, i;

    /* 设置数据 */
    if(ptypeFrame->get == 0)
    {
        cFeedFrameAddInt(ptypeFrame->ID, FEED_FRAME_ERROR_ACCESS);
    }
    /* 获取数据 */
    else
    {
        if((ptypeFrame->type == FEED_FRAME_TYPE_INT) && (ptypeFrame->length <= 4))
        {
            for(iValue = 0, i = 0; i < ptypeFrame->length; ++i)
            {
                iValue |= (uint32_t)ptypeFrame->datas[i] << (8 * i);
            }

            printf("cFeedIDHeartbeat: %d\r\n", (int)iValue);
        }
    }

    return (ptypeFrame->get != 0) ? 0 : FEED_FRAME_ERROR_ACCESS;
}

static int8_t cFeedIDSystemState(void *pvDatas)
{
    FeedFrameType *ptypeFrame = pvDatas;

    /* 设置数据 */
    if(ptypeFrame->get == 0)
    {
    }
    /* 获取数据 */
    else
    {
        printf("cFeedIDSystemState: %d\r\n", ptypeFrame->datas[0]);
    }

    return 0;
}

static int8_t cFeedIDFrameMcuMTU(void *pvDatas)
{
    FeedFrameType *ptypeFrame = pvDatas;
    ParametersType *ptypeParameters = ptypeParametersInfoGet();
    int32_t iValue, i;

    /* 设置数据 */
    if(ptypeFrame->get == 0)
    {
        cFeedFrameAddInt(ptypeFrame->ID, FEED_FRAME_ERROR_ACCESS);
    }
    /* 获取数据 */
    else
    {
        if((ptypeFrame->type == FEED_FRAME_TYPE_INT) && (ptypeFrame->length <= 2))
        {
            for(iValue = 0, i = 0; i < ptypeFrame->length; ++i)
            {
                iValue |= (uint32_t)ptypeFrame->datas[i] << (8 * i);
            }
            ptypeParameters->frameMcuMtu = iValue;
        }
    }

    return 0;
}

static int8_t cFeedIDAll(void *pvDatas)
{
    FeedFrameType *ptypeFrame = pvDatas;

    /* 设置数据 */
    if(ptypeFrame->get == 0)
    {
        cFeedFrameAddInt(ptypeFrame->ID, FEED_FRAME_ERROR_ACCESS);
    }
    /* 获取数据 */
    else
    {
        cFeedFrameAddInt(ptypeFrame->ID, FEED_FRAME_ERROR_ACCESS);
    }

    return 0;
}

/* 系统 回调函数列表 */
static FeedIDCallType g_typeFeedID[] = {
    /* 通用协议 */
    {.ID = 0xFFF,   .func = cFeedIDAll},

    {.ID = 0,       .func = cFeedIDHeartbeat},
    {.ID = 1,       .func = cFeedIDSystemState},
    {.ID = 2,       .func = cFeedIDFrameMcuMTU},
};

int8_t cFeedIDDecode(void *pvDatas)
{
    FeedFrameType *ptypeFrame = pvDatas;
    int32_t i;

    for(i = 0; i < (sizeof(g_typeFeedID) / sizeof(g_typeFeedID[0])); ++i)
    {
        if(ptypeFrame->ID == g_typeFeedID[i].ID)
        {
            /* 设置、获取数据 */
            return g_typeFeedID[i].func(ptypeFrame);
        }
    }

    return 1;
}
